import { Ref } from "vue";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { checkUpdatePasswordApi, loginApi } from "@/api/login";
import { setAuthent } from "@/utils/auth";
import { getLoginBgApi } from "@/api/common";
export default function ModifyPassword(state: { dialogOpts: Base.DialogOpts; formState: Base.GeneraDataType; staticResource: Ref<Base.GeneraDataType> }) {
  const { dialogOpts, formState, staticResource } = state;

  const router = useRouter();
  const onFinish = async (values: any) => {
    const { username, password } = values;
    const { clientType } = formState;
    // const params = window.location.search;
    // const paramsArr = params.split("clientType=");
    // let clientType;
    // if (paramsArr.length > 1) {
    //   clientType = paramsArr[paramsArr.length - 1];
    // }

    const getLoginStatus: any = await loginApi({
      password,
      username: username,
      clientType: clientType ? clientType : "MANAGE"
    });

    const { code, data } = getLoginStatus;

    if (code === 200) {
      await setAuthent("token", String(data));
      const checkUpdatePassword: any = await checkUpdatePasswordApi();

      const { code: checkCode, data: checkData } = checkUpdatePassword;

      if (checkCode === 200 && !checkData) {
        router.push("/");
      } else {
        message.error("身份信息过期,请修改密码后再登录");
        modifyPasswordHandle();
      }
    }
  };

  // 重置密码
  const modifyPasswordHandle = () => {
    dialogOpts.title = `重置密码`;
    dialogOpts.width = "520px";
    dialogOpts.component = "ChangePassword";
    dialogOpts.passData = formState.username;
    dialogOpts.type = 1;
    dialogOpts.visible = true;
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("===>error", errorInfo);
  };

  const init = () => {
    const params = window.location.search;
    const paramsArr = params.split("clientType=");
    if (paramsArr.length > 1) {
      formState.clientType = paramsArr[paramsArr.length - 1];
    }
    getLoginBgApi().then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        staticResource.value = data;
      }
    });
  };
  return {
    modifyPasswordHandle,
    onFinish,
    init,
    onFinishFailed
  };
}
